<template>
  <div class="cluster recovery">
    <a-card style="width: 100%" v-show="addEmployeeVisible === false">
      <p slot="title" class="cardTitles">
        <span>考试创编</span>
        <a-button
          v-if="type === 1"
          type="primary"
          style="float: right"
          @click="backClick"
          >返回</a-button
        >
      </p>
      <div class="paper-content">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          v-bind="formLayout"
        >
          <a-form-model-item label="考试名称" prop="name">
            <a-input v-model="form.name" autocomplete="off" />
          </a-form-model-item>
          <a-form-model-item label="时间设置" prop="dateTime">
            <a-range-picker
              :show-time="{ format: 'HH:mm' }"
              format="YYYY-MM-DD HH:mm:ss"
              @change="onChange"
              @ok="onOk"
              v-model="form.dateTime"
              style="width: 350px"
            />
          </a-form-model-item>
          <a-form-model-item label="可考试次数">
            <a-input-number
              v-model="form.tryTimes"
              style="width: 350px"
              :min="1"
            />
          </a-form-model-item>
          <a-form-model-item label="及格分数">
            <a-input-number
              v-model="form.passScore"
              style="width: 350px"
              :min="1"
              :max="100"
            />
          </a-form-model-item>
          <a-form-model-item label="站段" prop="section">
            <a-select v-model="form.section" style="width: 350px">
              <a-select-option v-for="section in sectionData" :key="section">
                {{ section }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="类型" prop="type">
            <a-select v-model="form.type" style="width: 350px">
              <a-select-option v-for="type in typeData" :key="type">
                {{ type }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="选择题目" prop="selectId">
            <span class="btn-item" style="float: right" @click="addTest"
              >选择模板</span
            >
            <span
              class="btn-item"
              style="float: right; margin-right: 10px"
              @click="addClick"
              >选择题目</span
            >
            <div class="questionTable">
              <a-table
                bordered
                :columns="columns"
                :data-source="form.questions"
                :pagination="false"
                rowKey="id"
              >
                <template slot-scope="text, record, index" slot="action">
                  <a class="tools" @click="deleteItem(index)">删除</a>
                </template>
              </a-table>
            </div>
          </a-form-model-item>
          <a-form-model-item label="参考员工" prop="examineeList">
            <span class="btn-item" style="float: right" @click="selectEmployee"
              >选择考生</span
            >
            <div class="examinee">
              <a-table
                bordered
                :columns="examineeColumns"
                :data-source="form.examineeList"
                :pagination="pagination"
                rowKey="id"
              >
                <template slot-scope="text, record" slot="action">
                  <a class="tools" @click="deleteExaminee(record)">删除</a>
                </template>
              </a-table>
            </div>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="onSubmit">提交 </a-button>
            <a-button style="margin-left: 10px" @click="resetForm">
              重置
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-card>
    <addEmployee
      :addEmployeeVisible="addEmployeeVisible"
      v-show="addEmployeeVisible !== false"
      @back="back"
      @saveSelectEmployee="saveSelectEmployee"
    />
    <addTestPaper
      :testPaperVisible="testPaperVisible"
      @closeFunc="testPaperVisible = false"
      @updateAddInform="updateAddInform"
    />
    <add-question
      :questionVisible="questionVisible"
      @selectQuestion="selectQuestion"
      @closeFunc="questionVisible = false"
    />
  </div>
</template>

<script>
import {
  addTemplate,
  updateTemplate,
  getTemplateDetail,
} from "@/api/templates";
import {
  addExamTasks,
  getExamTasksDetail,
  getExamTasksStu,
  updateExamTasksStu,
  updateExamTasks,
} from "@/api/examination";
import { getSectionArr, objectRepeat } from "@/assets/js/utils";
import question from "@/assets/json/questionList.js";
import { paging } from "assets/js/mixin";
import addTestPaper from "components/configuration/examination/addTestPaper";
import addEmployee from "components/configuration/examination/addEmployee";
import addQuestion from "components/configuration/testPaper/addQuestion";
import moment from "moment";
import { mapMutations } from "vuex";
export default {
  mixins: [paging],
  components: {
    addTestPaper,
    addEmployee,
    addQuestion,
  },
  data() {
    return {
      questionVisible: false,
      addEmployeeVisible: false, //1是考试添加页面2是选择考生界面
      //弹框
      testPaperVisible: false,
      sectionData: getSectionArr(),
      typeData: ["非正常行车"],
      //选中的id
      selectId: [],
      form: {
        name: "",
        section: "",
        type: "非正常行车",
        tryTimes: 1,
        dateTime: undefined,
        testList: [],
        questions: [],
        paperQuestion: [],
        examineeList: [],
        workerIDs: [],
        passScore: 60, //及格分数
      },
      columns: [
        {
          title: "题目id",
          dataIndex: "id",
          scopedSlots: { customRender: "id" },
        },
        {
          title: "题目内容",
          dataIndex: "question",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      examineeColumns: [
        {
          title: "工号",
          dataIndex: "workerID",
        },
        {
          title: "姓名",
          dataIndex: "name",
        },
        {
          title: "性别",
          dataIndex: "sex",
        },
        {
          title: "站段",
          dataIndex: "section",
        },
        {
          title: "班组",
          dataIndex: "group",
        },
        {
          title: "车间",
          dataIndex: "shop",
        },
        {
          title: "职位",
          dataIndex: "occupation",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      formLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      },
      rules: {
        name: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
        section: [{ required: true, message: "请选择站段", trigger: "change" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        dateTime: [
          { required: true, message: "请选择考试时间范围", trigger: "change" },
        ],
        // selectId:[{ required: true, message: "请选择题目"}],
        examineeList: [{ required: true, message: "请选择参考员工" }],
      },
      type: 0, //0是新增1是编辑
      id: "",
    };
  },
  mounted() {
    this.type = this.$route.query.type == undefined ? 0 : 1;
    this.id = this.$route.query.id;
    if (this.type == 1) {
      this.getBaseMessage();
      this.getStu();
    } else {
      this.setSelectRows([]);
      this.updateSelectEmployee([]);
      if (localStorage.getItem("selectKey")) {
        localStorage.removeItem("selectKey");
      }
    }
  },
  methods: {
    //增加题目弹框
    addClick() {
      localStorage.setItem("selectKey", JSON.stringify(this.selectId));
      this.questionVisible = true;
    },
    //更新题目
    selectQuestion(val) {
      this.form.questions = val.selectedRows;
      this.form.questions = objectRepeat(this.form.questions);
      console.log(this.form.questions);
      this.getSelectId();
    },
    //获取选择的id
    getSelectId() {
      var arr = [];
      this.form.questions.forEach((item) => {
        arr.push(item.id);
      });
      this.selectId = arr;
    },
    deleteItem(index) {
      this.form.questions.splice(index, 1);
      this.selectId.splice(index, 1);
      localStorage.setItem("selectKey", JSON.stringify(this.selectId));
    },
    backClick() {
      this.$router.go(-1);
    },
    ...mapMutations({
      setSelectRows: "SET_SELECT_ROWS",
      updateSelectEmployee: "SET_EMPLOYEE",
    }),
    //更新选择的试卷
    updateAddInform() {
      this.testPaperVisible = false;
      this.form.testList = this.$store.state.testSelectedRows;
      console.log(this.form.testList[0].id);
      this.getTemplate(this.form.testList[0].id);
    },
    //获取基本信息
    getBaseMessage() {
      getExamTasksDetail(this.id)
        .then((res) => {
          var nowDate = moment().format("YYYY-MM-DD HH:mm:ss");
          if (moment(res.data.startTime).isBefore(nowDate)) {
            //this.$message.error("修改可能会影响已有成绩记录");
            this.$warning({
              title: "修改可能会影响已有成绩记录",
            });
          }
          var arrTime = [];
          arrTime.push(res.data.startTime);
          arrTime.push(res.data.endTime);
          this.form.dateTime = arrTime;
          this.form.name = res.data.name;
          this.form.section = res.data.section;
          this.form.tryTimes = res.data.tryTimes;
          this.form.type = res.data.examType;
          this.form.passScore = res.data.passScore;
          var questionList = question();
          //处理数据把题目id转换成题目
          questionList.forEach((item, index) => {
            for (var i = 0; i < res.data.paper.length; i++) {
              if (res.data.paper[i] == item.id) {
                this.form.questions.push(item);
              }
            }
          });
          this.selectId = res.data.paper;
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    getStu() {
      getExamTasksStu(this.id)
        .then((res) => {
          this.form.examineeList = res.data.addedEmployess;
          this.updateSelectEmployee(
            JSON.parse(JSON.stringify(this.form.examineeList))
          );
          var workIdArr = [];
          this.form.examineeList.forEach((item, index) => {
            workIdArr.push(item.workerID);
          });
          this.workerIDs = workIdArr;
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    //获取试卷详情为了获取试卷题目
    getTemplate(id) {
      getTemplateDetail(id)
        .then((res) => {
          this.paperQuestion = res.data.questions;
          console.log(this.paperQuestion);
          var questionList = question();
          this.form.questions = [];
          //处理数据把题目id转换成题目
          questionList.forEach((item, index) => {
            for (var i = 0; i < res.data.questions.length; i++) {
              if (res.data.questions[i] == item.id) {
                this.form.questions.push(item);
              }
            }
          });
          this.form.questions = objectRepeat(this.form.questions);
          this.getSelectId();
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    //增加试卷弹框
    addTest() {
      this.testPaperVisible = true;
    },

    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.selectId.length == 0) {
            this.$message.error("请添加题目");
            return;
          }
          if (this.workerIDs.length == 0) {
            this.$message.error("请选择考生");
            return;
          }
          var params = {
            name: this.form.name,
            section: this.form.section,
            examType: this.form.type,
            tryTimes: this.form.tryTimes,
            startTime: this.form.dateTime[0] ? this.form.dateTime[0] : "",
            endTime: this.form.dateTime[1] ? this.form.dateTime[1] : "",
            paper: this.selectId,
            workerIDs: this.workerIDs,
            passScore: this.form.passScore,
          };
          if (this.type == 1) {
            params.examID = this.id;
            this.updateSubmit(params);
          } else {
            this.addSubmit(params);
          }
        } else {
          return false;
        }
      });
    },
    addSubmit(params) {
      addExamTasks(params)
        .then((res) => {
          if (res.code === 2) {
            this.$message.error(res.msg);
            return false;
          }
          if (res.data.ok) {
            this.$message.success("添加成功");
            this.$router.push("/console/configuration/examination/index");
          } else {
            console.log(res.data.errDatas[0].err);
            this.$message.error(res.data.errDatas[0].err);
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    updateSubmit(params) {
      updateExamTasks(params)
        .then((res) => {
          this.$message.destroy();
          // this.$message.success("编辑成功");
          // localStorage.removeItem("selectKey");
          // this.$router.push("/console/configuration/examination/index");
          this.$message.destroy();
          this.$message.success("编辑成功");
          localStorage.removeItem("selectKey");
          this.$router.push("/console/configuration/examination/index");
          //this.updateSubmitStu(params)
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    updateSubmitStu(params) {
      updateExamTasksStu(params)
        .then((res) => {
          this.$message.destroy();
          this.$message.success("编辑成功");
          localStorage.removeItem("selectKey");
          this.$router.push("/console/configuration/examination/index");
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.selectId = [];
      this.form.questions = [];
      this.form.paperQuestion = [];
    },
    onChange(value, dateString) {
      console.log("Formatted Selected Time: ", dateString);
      this.form.dateTime = dateString;
    },
    onOk(value) {
      console.log("onOk: ", value);
    },
    //删除试卷
    deleteTest(index) {
      this.form.testList.splice(index, 1);
      this.setSelectRows(this.form.testList);
    },
    //删除考生
    deleteExaminee(record) {
      for (var i = 0; i < this.form.examineeList.length; i++) {
        if (this.form.examineeList[i].id === record.id) {
          this.form.examineeList.splice(i, 1);
        }
      }
      this.updateSelectEmployee(this.form.examineeList);
      this.getWorkId(this.form.examineeList);
    },
    //选择考生
    selectEmployee() {
      this.addEmployeeVisible = true;
    },
    //返回页面
    back() {
      this.addEmployeeVisible = false;
    },
    //保存选择考生
    saveSelectEmployee(val) {
      this.addEmployeeVisible = false;
      this.form.examineeList = val;
      this.getWorkId(this.form.examineeList);
    },
    //获取考生的工作号
    getWorkId(data) {
      var workIdArr = [];
      data.forEach((item, index) => {
        workIdArr.push(item.workerID);
      });
      this.workerIDs = workIdArr;
    },
  },
};
</script>

<style lang="stylus" scoped>
.formDiv {
  .lable {
    margin-right: 10px;
  }
}

.upload {
  float: right;
}

.recovery {
  height: 100%;
}

.paper-content {
  width: 85%;

  .questionTable, .examinee {
    margin-top: 42px;
  }

  .card {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;

    li {
      position: relative;
      padding: 15px 0;
      margin-bottom: 15px;
    }

    .questionIndex {
      float: left;
      font-size: 14px;
      color: #606266;
      padding: 0 12px 0 0;
      width: 80px;
      font-weight: bold;
    }

    .questionContent {
      margin-left: 60px;
      font-size: 14px;
      color: #303133;
      width: 85%;
    }

    .delectBtn {
      color: #1890ff;
      position: absolute;
      top: 15px;
      right: 0;
      cursor: pointer;
    }
  }
}

.ant-card-body {
  height: 100%;
}

.btn-item {
  line-height: 32px;
  position: relative;
  display: inline-block;
  font-weight: 400;
  white-space: nowrap;
  text-align: center;
  background-image: none;
  border: 1px solid transparent;
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.015);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  touch-action: manipulation;
  height: 34px;
  padding: 0 15px;
  font-size: 14px;
  border-radius: 4px;
  color: rgba(0, 0, 0, 0.65);
  background-color: #fff;
  border-color: #d9d9d9;
  cursor: pointer;
}
</style>